//
//  Timer.swift
//  CooperSwift
//
//  Created by 计海峰 on 2022/8/30.
//

import Foundation
import RxSwift

/// 倒计时
/// - Parameters:
///   - second: 总共秒
///   - immediately: 是否立即执行
///   - duration: 过程
/// - Returns: Single
public func countdownTimer(second: Int, immediately: Bool = true, duration: ((Int) -> Void)?) -> Single<Void> {
    guard second > 0 else { return Single<Void>.just(())}
    if immediately {
        duration?(second)
    }
    return Observable<Int>.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
        .map{ second-(immediately ? ($0 + 1) : $0) }
        .take(second+(immediately ? 0 : 1))
        .do(onNext: { (index) in
            duration?(index)
        })
        .filter{ return $0 == 0 }
        .map{_ in return () }
        .asSingle()
}

